package com.renfei.ffmpegvideoplayer.opengl;

import android.content.Context;
import android.opengl.GLES20;
import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class OpenGLUtil {

    private static final String TAG = "OpenGLUtil";

    public static String loadRawShaderSource(Context context, int resourceId) {
        InputStream inputStream = context.getResources().openRawResource(resourceId);
        InputStreamReader isr = new InputStreamReader(inputStream);
        BufferedReader reader = new BufferedReader(isr);
        StringBuffer sb = new StringBuffer();
        String line = "";
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line).append("\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }

    public static int loadShader(int shaderType,String shaderSource){

        int shader = GLES20.glCreateShader(shaderType);
        if (shader!=0){
            GLES20.glShaderSource(shader,shaderSource);
            GLES20.glCompileShader(shader);

            int [] compile=new int[1];
            GLES20.glGetShaderiv(shader,GLES20.GL_COMPILE_STATUS,compile,0);

            if (compile[0]!=GLES20.GL_TRUE){
                Log.e(TAG, "glCompileShader: error  ");
                GLES20.glDeleteShader(shader);
                shader=0;
            }
        }
        return shader;
    }


    public static int createProgram(String vertexShaderSource,String fragmentShaderSource){

        int vertexShaderId=loadShader(GLES20.GL_VERTEX_SHADER,vertexShaderSource);
        if (vertexShaderId==0){
            Log.e(TAG, "vertexShaderId: create error ");
            return 0;
        }
        int fragmentShaderId=loadShader(GLES20.GL_FRAGMENT_SHADER,fragmentShaderSource);
        if (fragmentShaderId==0){
            Log.e(TAG, "fragmentShaderId: create error ");
            return 0;
        }
        int program=GLES20.glCreateProgram();

        if (program!=0){
            GLES20.glAttachShader(program,vertexShaderId);
            GLES20.glAttachShader(program,fragmentShaderId);
            GLES20.glLinkProgram(program);
            int [] linkStatus=new int[1];
            GLES20.glGetProgramiv(program,GLES20.GL_LINK_STATUS,linkStatus,0);

            if (linkStatus[0]!=GLES20.GL_TRUE){
                Log.e(TAG, "glLinkProgram: on error");
                GLES20.glDeleteProgram(program);
                program=0;
            }
        }
        return program;
    }

}
